package com.onairm.baselibrary.mvp.base;

import android.content.Context;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by bqy on 2018/3/28.
 */

public class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V> {

    private V viewProxy;
    private V view;
    protected Context context;

    public V getView() {
        return viewProxy;
    }

    @Override
    public void attachView(V view) {
        this.view = view;
        Class<?>[] interfaces = view.getClass().getInterfaces();
        try {
            viewProxy = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(),
                    interfaces,
                    new ProxyInvocationHandler<V>(view));
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void detachView() {
        this.view = null;
    }


    private class ProxyInvocationHandler<V extends MvpView> implements InvocationHandler {
        private V view;
        public ProxyInvocationHandler(V view) {
            this.view = view;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (view != null) {
                return method.invoke(view, args);
            }
            throw new NullPointerException("空指针");
        }
    }
}
